﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Data;
using System.Linq;

using ECCIT;
using ECCIT.Data;
using ECCIT.Business.DAL;

using OgilvyOne.UKNow.Common;
using OgilvyOne.UKNow.Globalization;
using OgilvyOne.UKNow.Utility;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.IDAL;
using OgilvyOne.Utility;
using SortOrder = ECCIT.SortOrder;

namespace OgilvyOne.UKNow.DAL
{
    public class EventsVideoDAL : UKNowBaseDAL, IDALEventsVideo
    {
        private const string TBL_NAME = "UKNOW_EVENTS_VIDEO";
        private const string COL_LANG_ID = "COL_LANG_ID";
        private const string COL_EVENTS_VIDEO_ID = "COL_EVENTS_VIDEO_ID";
        private const string COL_EVENTS_ID = "COL_EVENTS_ID";
        private const string COL_EVENTS_VIDEO_NAME = "COL_EVENTS_VIDEO_NAME";
        private const string COL_EVENTS_VIDEO_PATH = "COL_EVENTS_VIDEO_PATH";
        private const string COL_EVENTS_VIDEO_EXT = "COL_EVENTS_VIDEO_EXT";
        private const string COL_EVENTS_VIDEO_TYPE = "COL_EVENTS_VIDEO_TYPE";
        private const string COL_EVENTS_VIDEO_DESC = "COL_EVENTS_VIDEO_DESC";
        private const string COL_EVENTS_VIDEO_TAG = "COL_EVENTS_VIDEO_TAG";
        private const string COL_EVENTS_VIDEO_STATE = "COL_EVENTS_VIDEO_STATE";
        private const string COL_EVENTS_VIDEO_IMG_PATH = "COL_EVENTS_VIDEO_IMG_PATH";
        private const string COL_EVENTS_VIDEO_ORDER = "COL_EVENTS_VIDEO_ORDER";
        private const string COL_EVENTS_VIDEO_RECO = "COL_EVENTS_VIDEO_RECO";
        private const string COL_EVENTS_VIDEO_INSERT_TIME = "COL_EVENTS_VIDEO_INSERT_TIME";
        private const string COL_EVENTS_VIDEO_UPDATE_TIME = "COL_EVENTS_VIDEO_UPDATE_TIME";

        public override string TableName { get { return TBL_NAME; } }

        public override Type ModelType { get { return typeof(EventsVideoModel); } }

        [PrimaryKey]
        public IField LanguageID { get { return FieldFactory.Create(ModelType, "LanguageID", ColumnFactory.CreateColumn(COL_LANG_ID, DataType.Int)); } }
        [PrimaryKey]
        public IField ID { get { return FieldFactory.Create(ModelType, "ID", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_ID, DataType.Int)); } }
        public IField EventsID { get { return FieldFactory.Create(ModelType, "EventsID", ColumnFactory.CreateColumn(COL_EVENTS_ID, DataType.Int)); } }
        public IField Name { get { return FieldFactory.Create(ModelType, "Name", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_NAME, DataType.String, 200)); } }
        public IField Path { get { return FieldFactory.Create(ModelType, "Path", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_PATH, DataType.String, 200)); } }
        public IField Extension { get { return FieldFactory.Create(ModelType, "Extension", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_EXT, DataType.String, 20)); } }
        public IField Type { get { return FieldFactory.Create(ModelType, "Type", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_TYPE, DataType.Int)); } }
        public IField Description { get { return FieldFactory.Create(ModelType, "Description", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_DESC, DataType.String, 500)); } }
        public IField Tag { get { return FieldFactory.Create(ModelType, "Tag", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_TAG, DataType.String, 200)); } }
        public IField State { get { return FieldFactory.Create(ModelType, "State", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_STATE, DataType.Int)); } }
        public IField ImagePath { get { return FieldFactory.Create(ModelType, "ImagePath", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_IMG_PATH, DataType.String, 200)); } }
        public IField Order { get { return FieldFactory.Create(ModelType, "Order", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_ORDER, DataType.Int)); } }
        public IField IsRecommendation { get { return FieldFactory.Create(ModelType, "IsRecommendation", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_RECO, DataType.Bit)); } }
        public IField InsertedTime { get { return FieldFactory.Create(ModelType, "InsertedTime", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_INSERT_TIME, DataType.DateTime)); } }
        public IField UpdatedTime { get { return FieldFactory.Create(ModelType, "UpdatedTime", ColumnFactory.CreateColumn(COL_EVENTS_VIDEO_UPDATE_TIME, DataType.DateTime)); } }

        public override IField[] InsertFields { get { return new IField[] { LanguageID, ID, EventsID, Name, Path, Extension, Type, Description, Tag, State, ImagePath, Order, IsRecommendation, InsertedTime, UpdatedTime }; } }
        public override IField[] SelectFields { get { return InsertFields; } }
        public override IField[] UpdateFields { get { return new IField[] { LanguageID, ID, EventsID, Name, Path, Extension, Type, Description, Tag, State, ImagePath, Order, IsRecommendation, UpdatedTime }; } }

        public EventsVideoDAL() { }

        public EventsVideoDAL(LanguageType languageType) { this.Language = LanguageFactory.Create(languageType); }

        private void SetForeignKeyModel(EventsVideoModel model)
        {
            if (model == null) return;
            model.FileType = (model.Type==3) ? 3 : 2;
            model.ThumbnailImagePath = model.ImagePath;
            model.Events = new EventsDAL(this.Language.LanguageType).GetEventsModelByID(model.EventsID);
        }

        #region IDALEventsVideo Members

        public EventsVideoModel GetEventsVideoModelByID(int? id)
        {
            EventsVideoModel model = (EventsVideoModel)GetModelByPrimaryKey(this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });
            SetForeignKeyModel(model);
            return model;
        }

        public IList<EventsVideoModel> GetAllEventsVideoModels(int? eventsID)
        {
            IDataParameter[] parms = DBHelper.GetDataParameters(new IField[] { EventsID, LanguageID });
            parms[0].Value = eventsID;
            parms[1].Value = (int)this.Language.LanguageType;

            string whereClause = "WHERE " + COL_EVENTS_ID + "=#" + COL_EVENTS_ID + " AND " + COL_LANG_ID + "=#" + COL_LANG_ID;
            IList<EventsVideoModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc)), parms).List.Cast<EventsVideoModel>().ToList();
            foreach (EventsVideoModel model in models)
                SetForeignKeyModel(model);

            return models;
        }

        public PagingList GetEventsVideoModelsByKeywords(string keywordString, PagingParameter pagingParams)
        {
            JoinedString keywords = new JoinedString(keywordString, " ");
            StringBuilder highLevelBuilder = new StringBuilder();
            StringBuilder lowLevelBuilder = new StringBuilder();
            foreach (string keyword in keywords)
            {
                if (string.IsNullOrEmpty(keyword)) continue;
                if (highLevelBuilder.Length > 0)
                    highLevelBuilder.Append(" and ");
                highLevelBuilder.AppendFormat(" {0} like '%{1}%' ", COL_EVENTS_VIDEO_TAG, keyword);

                if (lowLevelBuilder.Length > 0)
                    lowLevelBuilder.Append(" or ");
                lowLevelBuilder.AppendFormat(" ({0} like '%{1}%') ", COL_EVENTS_VIDEO_TAG, keyword);
            }

            string whereClause = string.Format("where {0}={1} and {2}={3} ", COL_EVENTS_VIDEO_STATE, 1, COL_LANG_ID, (int)this.Language.LanguageType);
            if (highLevelBuilder.Length > 0)
                whereClause += " and ((" + highLevelBuilder.ToString() + ") or " + lowLevelBuilder.ToString() + ")";
            IList<EventsVideoModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsVideoModel>().ToList();

            List<MediaFileModel> lmm = new List<MediaFileModel>();
            MediaFileModel mfm = null;
            List<string> imageNames = new List<string>();
            EventsDAL dal = new EventsDAL(this.Language.LanguageType);
            EventsModel eventsModel = null;
            foreach (EventsVideoModel evm in models)
            {
                mfm = new MediaFileModel();
                mfm.ID = evm.ID;
                mfm.LanguageID = evm.LanguageID;
                mfm.Name = evm.Name;
                mfm.Path = evm.ThumbnailImagePath;
                mfm.MediType = 1;//活动图片

                // 对于同名的图片，只显示一个搜索结果
                if (!imageNames.Contains(evm.ThumbnailImagePath))
                {
                    eventsModel = dal.GetEventsModelByID(evm.EventsID);
                    if (eventsModel == null) continue;
                    mfm.HtmlFileName = (string.IsNullOrEmpty(eventsModel.HtmlFileName)) ? eventsModel.ID + ".html" : eventsModel.HtmlFileName;

                    lmm.Add(mfm);
                    imageNames.Add(evm.ThumbnailImagePath);
                    mfm = null;
                }
            }

            PageTools page = new PageTools(lmm, pagingParams.CurrentPageIndex+1, pagingParams.PageSize);

            return new PagingList(page.DataList, lmm.Count);
        }

        public IList<EventsVideoModel> GetPublishedEventsVideoModels(int? eventsID)
        {
            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_VIDEO_STATE, 1, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_ID, eventsID, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));
            /*
             * 代码修改：
             * 修改人员：刘扬
             * 修改日期：2012-04-08
             * 修改原因：原先图片的是否推荐标志位现用于是否在Gallery显示，所以获取发布状态图片需要增加过滤条件
             * */
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_VIDEO_RECO, 0, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();

            IList<EventsVideoModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(Order.PropertyName + "," + UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsVideoModel>().ToList();
            foreach (EventsVideoModel model in models)
                SetForeignKeyModel(model);
            return models;
        }

        public IList<EventsVideoModel> GetPublishedGalleryVideoModelsByEventsID(int? eventsID)
        {
            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_VIDEO_STATE, 1, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_ID, eventsID, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_VIDEO_RECO, 1, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();

            IList<EventsVideoModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(Order.PropertyName + "," + UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsVideoModel>().ToList();
            foreach (EventsVideoModel model in models)
                SetForeignKeyModel(model);
            return models;
        }

        public IList<EventsVideoModel> GetPublishedGalleryVideoModels()
        {
            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_VIDEO_STATE, 1, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_VIDEO_RECO, 1, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();

            IList<EventsVideoModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsVideoModel>().ToList();
            foreach (EventsVideoModel model in models)
                SetForeignKeyModel(model);
            return models;
        }

        public int GetTotalCountByEventsID(int? eventsID)
        {
            string cmd = string.Format("select count({0}) from {1} where {2}={3} and {4}={5} and {6}={7}",
                COL_EVENTS_VIDEO_ID, TBL_NAME, COL_LANG_ID, (int)this.Language.LanguageType, COL_EVENTS_ID, eventsID, COL_EVENTS_VIDEO_STATE, 1);

            object obj = DBHelper.ExecuteScalar(cmd);
            return (int)obj;
        }
        /*
           * 代码修改：
           * 修改人员：穆凤凤
           * 修改日期：2012-04-11
           * 修改原因：当某一活动设置为未发布时,其相关的视频发布状态均应为未发布,因此,增加根据活动ID修改活动视频的发布状态的方法
           * */
        public bool editPubState(int eid)
        {
            string sqlstr = string.Format("update dbo.UKNOW_EVENTS_VIDEO set COL_EVENTS_VIDEO_STATE =0 where COL_LANG_ID={0} and COL_EVENTS_ID={1}", (int)this.Language.LanguageType, eid);
            int i = DBHelper.ExecuteNonQuery(sqlstr);
            if (i > 0)
            { return true; }
            else
            { return false; }
        }
        public ResultInfo Save(EventsVideoModel modelInfo)
        {
            if (modelInfo == null) throw new ArgumentNullException("modelInfo");

            ResultInfo result = new ResultInfo(false);

            try
            {
                int rowsAffected = 0;
                if (modelInfo.ID == null)   // insert
                {
                    modelInfo.ID = SqlUtil.GetMaxRecordID(TableName, COL_EVENTS_VIDEO_ID, COL_LANG_ID, (int)this.Language.LanguageType);
                    //modelInfo.State = 0;    // 强制将视频状态置为未发布
                    modelInfo.InsertedTime = DateTime.Now;
                    modelInfo.UpdatedTime = DateTime.Now;
                    rowsAffected = Insert(modelInfo, null);
                }
                else // update
                {
                    modelInfo.UpdatedTime = DateTime.Now;
                    rowsAffected = UpdateByPrimaryKey(modelInfo, null);
                }

                if (rowsAffected > 0)
                {
                    result.Message = "视频数据保存成功！";
                    result.Result = true;
                    result.ReturnObject = modelInfo;
                }
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Message = string.Format("保存视频数据时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo Delete(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);
            using (IDbConnection conn = DBHelper.GetDbConnection())
            {
                conn.Open();
                IDbTransaction trans = conn.BeginTransaction();
                try
                {
                    foreach (int? id in idList)
                        DeleteModelByPrimaryKey(trans, this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });

                    trans.Commit();
                    result.Result = true;
                    result.Message = "视频数据删除成功！";
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    result.Message = string.Format("删除视频数据时发生异常。异常信息：{0}", ex.Message);
                }
                finally
                {
                    trans.Dispose();
                }
            }

            return result;
        }

        public ResultInfo DeleteByEventsID(IDbTransaction trans, int? eventsID)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                string whereClause = string.Format("where {0}={1} and {2}={3}", COL_LANG_ID, (int)this.Language.LanguageType, COL_EVENTS_ID, eventsID);
                Delete(trans, whereClause);
                result.Result = true;
                result.Message = Language.GetAlertMessage(ModelType, Enums.Action.Delete, Enums.ActionResult.Success);
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Message = Language.GetAlertMessage(ModelType, Enums.Action.Delete, Enums.ActionResult.Exception, ex);
            }

            return result;
        }

        public ResultInfo Publish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 1;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_EVENTS_VIDEO_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "视频发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("发布视频时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo UnPublish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 0;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_EVENTS_VIDEO_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "视频取消发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("取消发布视频时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }
        public IList<EventsVideoModel> GetAllPublishedEventsRecoVideoModels()
        {


            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_VIDEO_STATE, 1, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_VIDEO_RECO, 1, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));
            string whereClause = builder.ToSqlCommand();
            IList<EventsVideoModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsVideoModel>().ToList();

           
            return models;
        }

        /// <summary>
        /// 插入视频信息
        /// </summary>
        /// <param name="vid"></param>
        /// <param name="vNameOld"></param>
        /// <param name="vNamePath"></param>
        public void InsertFlvBase(string vid,string vNameOld, string vNamePath)
        {
             string sql = @"
                    insert into flv_Basic (vid,vNameOld,vNamePath,videoWidth,videoHeight,vCutImageWidth,vCutImageHeight,vConvertFlag)
                    values (@vid,@vNameOld,@vNamePath,400,350,240,180,'D')";
            IDataParameter[] parameters = {
					new SqlParameter("@vid", SqlDbType.NVarChar,200),
					new SqlParameter("@vNameOld", SqlDbType.NVarChar,200),
					new SqlParameter("@vNamePath", SqlDbType.NVarChar,200),
                  
					};
            parameters[0].Value = vid;
            //下面的这两个暂时不用
            parameters[1].Value = vNameOld;
            parameters[2].Value = vNamePath;
            DBHelper.ExecuteNonQuery(sql, parameters);
        }

        #endregion
    }
}
